package cn.dancepeak.employee.service.impl;

import cn.dancepeak.employee.domain.Employee;
import cn.dancepeak.employee.mapper.EmployeeMapper;
import cn.dancepeak.employee.query.EmployeeQuery;
import cn.dancepeak.employee.service.IEmployeeServiceImpl;
import cn.dancepeak.exception.BusinessException;
import cn.hutool.core.util.ObjectUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImplImpl implements IEmployeeServiceImpl {
    @Autowired
    private EmployeeMapper employeeMapper;
    @Override
    @Transactional
    public void add(Employee employee) {
        //判断是否注册过
        Employee employee1 = employeeMapper.selectByEmployeeName(employee.getUsername());
        if(ObjectUtil.isNotNull(employee1)){
            throw new BusinessException("用户已被注册");
        }
        //保存员工返回自增id
        employeeMapper.insert(employee);
        //保存员工的角色信息   需要employeeId 和 roleID
        employeeMapper.saveEmployeeRole(employee);
    }

    @Override
    @Transactional
    public void update(Employee employee) {
        //用户名不能修改   禁用  在前端写
        employeeMapper.updateById(employee);
        //数据库有脏数据 先删除在新增
        employeeMapper.deleteEmployeeRoleId(employee.getId());
        employeeMapper.saveEmployeeRole(employee);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        employeeMapper.deleteById(id);
        //删除员工要把他的角色中间表也删除
        employeeMapper.deleteEmployeeRoleId(id);
    }

    @Override
    @Transactional
    public void deleteByList(List<Long> ids) {
        employeeMapper.deleteByList(ids);
        for (Long id : ids) {
            //删除员工要把他的角色中间表也删除
            employeeMapper.deleteEmployeeRoleId(id);
        }
    }

    @Override
    public Employee getById(Long id) {
        return employeeMapper.selectById(id);
    }

    @Override
    public PageInfo<Employee> page(EmployeeQuery employeeQuery) {
        // 1.下面这句代码表示开启分页，会将紧挨着这句代码的下一次数据库执行进行分页，切记一定要放在要分页的SQL语句前面执行
        // 2.执行SQL语句带条件查询，SQL语句不需要进行分页
        PageHelper.startPage(employeeQuery.getCurrentPage(), employeeQuery.getPageSize());
        List<Employee> employee = employeeMapper.list(employeeQuery);
        // 3.将查询结果转换为PageInfo对象，PageInfo对象中有前端分页所需要的各种参数
        PageInfo<Employee> pageInfo = new PageInfo<>(employee);
        // 4.响应总条数和分页信息
        return pageInfo;
    }

    @Override
    @Transactional
    public void updateState(Employee employee) {
        employeeMapper.updateState(employee);
    }
}